//
//  PDFPageCell.swift
//  PDF2PNG
//
//  Created by Jarvis on 10/05/2017.
//  Copyright © 2017 Jarvis. All rights reserved.
//

import UIKit


let collectionViewMargin: CGFloat = 15
let pageCollectionCellWidth = (UIScreen.main.bounds.size.width - collectionViewMargin * 4) / 3


class PDFPageCell: UICollectionViewCell {
    
    var imageView: UIImageView!
    var checkbox: UIButton!
    var pageIndexLabel: UILabel!
    
    var enableSelect: Bool = false
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func prepareUI() {
        
        imageView = UIImageView()
        contentView.addSubview(imageView);
        imageView.contentMode = .scaleAspectFit
        imageView.snp.makeConstraints { (make) in
            make.width.equalTo(pageCollectionCellWidth)
            make.height.equalTo(pageCollectionCellWidth)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        checkbox = UIButton()
        contentView.addSubview(checkbox)
        checkbox.setImage(UIImage(named: "checkbox_selected"), for: .normal)
//        checkbox.setImage(UIImage(named: "checkbox_selected"), for: .selected)
        checkbox.addTarget(self, action: #selector(checkboxPressed(_:)), for: .touchUpInside)
//        checkbox.backgr oundColor = UIColor.black.withAlphaComponent(0.5)
        checkbox.snp.makeConstraints { (make) in
            make.edges.equalTo(imageView.snp.edges)
        }
        
        checkbox.isUserInteractionEnabled = false
        checkbox.isHidden = true
        
        
        pageIndexLabel = UILabel()
        contentView.addSubview(pageIndexLabel)
        pageIndexLabel.text = "- 0 -"
        pageIndexLabel.textColor = UIColor.darkGray
        pageIndexLabel.font = UIFont.systemFont(ofSize: 12)
        pageIndexLabel.textAlignment = .center
        pageIndexLabel.snp.makeConstraints { (make) in
            make.top.equalTo(imageView.snp.bottom)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
    }
    
    @objc func checkboxPressed(_ button: UIButton) {
        button.isSelected = !button.isSelected
        
    }
    
    
    //MARK: open functions
    open func setupPageInfo(newPageInfo: PageInfo) {
        
        imageView.image = newPageInfo.image
        pageIndexLabel.text = String(format: "- %d -", newPageInfo.index!)
        
        checkbox.isHidden = !newPageInfo.isSelected
    }

    open func setupPageInfo(newPageInfo: PageInfo, enableSelect: Bool) {
        
        imageView.image = newPageInfo.image
        pageIndexLabel.text = String(format: "- %d -", newPageInfo.index!)
        
        checkbox.isHidden = !(newPageInfo.isSelected && enableSelect)
    }
    
    
}
